import './message.html';

import { Template } from 'meteor/templating';

Template.App_message.onCreated(function(){
  let self = this;
  self.msgObj = new ReactiveVar({});
  self.visible = new ReactiveVar(false);
  self.autorun(function(){
     let msgObj = Session.get('appmessage');
     if (msgObj !=undefined ) {
       self.msgObj.set(msgObj);
       self.visible.set(true);
     }
     if (self.visible.get()) {
       setTimeout(function(){
          self.visible.set(false);
       }, 5000);
       Session.set("appmessage", undefined);
     }

  });
});

Template.App_message.helpers({
  headerMsg(){
    return Template.instance().msgObj.get().headerMsg;
  },
  extraHtml(){
    return Template.instance().msgObj.get().extraHtml;
  },
  visible(){
    if (Template.instance().visible.get()) {
      return ''
    }
    return 'hidden'
  },
  flagClass(){
    return Template.instance().msgObj.get().flagClass;
  }
});

Template.App_message.onRendered(function(){
  $('.message .close')
  .on('click', function() {
    $(this)
      .closest('.message')
      .transition('fade')
    ;
    Session.set("appmessage", undefined);
  })
;
});


export const Message = {
  sendSuccess: function(headerMsg, extraHtml){
    Session.set("appmessage", {
      headerMsg,
      extraHtml,
      flagClass: "positive"
    });
  },
  sendError: function(headerMsg, extraHtml){
    Session.set("appmessage", {
      headerMsg,
      extraHtml,
      flagClass: "negative"
    });
  },
  sendWarn: function(headerMsg, extraHtml){
    Session.set("appmessage", {
      headerMsg,
      extraHtml,
      flagClass: "warning"
    });
  }
};
